#!/bin/sh

NAME='antlion'
CONFIG="$NAME.ini"
PIDFILE="/var/run/overwatch/$NAME.pid"
DAEMON="./$NAME.php"
USER='www-data'
GROUP='www-data'

GetPid () {
	if ! [ -r "$PIDFILE" ]; then
		return 1
	fi
	PID="$(cat "$PIDFILE")"
	if ! kill -0 "$PID"; then
		return 1
	fi
	echo "$PID"
	return 0
}

Stop () {
	echo -n "Stopping $NAME... "
	if ! PID=$(GetPid); then
		echo "(ERROR) Couldn't determine daemon's PID, is it running?"
		return 1
	fi
	echo -n "[pid: $PID] "
	if ! kill -INT "$PID"; then
		echo "(ERROR) kill failed."
		return 1
	fi
	echo "OK."
	return 0
}
Start () {
	echo -n "Starting $NAME... "
	if PID=$(GetPid); then
		echo "(ERROR) Daemon is already running."
		return 1
	fi
	if ! "$DAEMON" -u="$USER" -g="$GROUP" "$@"; then
		echo "(ERROR) something went wrong, check the logs."
		return 1
	fi
	echo "(OK)."
	return 0
}
Reload () {
	echo -n "Reconfiguring $NAME... "
	if ! PID=$(GetPid); then
		echo "(ERROR) Couldn't determine daemon's PID, is it running?"
		return 1
	fi
	echo -n "[pid: $PID] "
	if ! kill -HUP "$PID"; then
		echo "(ERROR) kill failed."
		return 1
	fi
	echo "OK."
	return 0
}

CMD="$1"
shift
case "$CMD" in
	'stop')
		Stop
	;;
	'start')
		Start "$@"
	;;
	'restart')
		Stop
		Start "$@"
	;;
	'reload')
		Reload
	;;
	*)
		echo "Usage: $(basename "$0") { start | stop | restart | reload } [<daemon options>]"
	;;
esac
